﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using AllInOnePluginBL.Helpers;

namespace AllInOnePluginBL.FileHostingExtractors
{
    /// <summary>
    /// Summary description for MegaVideoExtractor
    /// </summary>
    public class MegaVideoExtractor : IFileHostingExtractor
    {
        private const string CONTROL_URI = "http://www.megavideo.com/xml/videolink.php?v={0}";
        private const string VIDEO_URL = "http://www.megavideo.com/?v={0}";
        private const string URL_REGEX = @"megavideo\.com.*?[v,d][=,/](.{8})";
        //private const string MEGAVIDEO_D_URL = "http://www.megavideo.com/?d={0}";
        private const string PREMIUM_URL = "http://www.megavideo.com/xml/player_login.php?u={0}&v={1}";
        private const string CHECK_PREMIUM_URL = "http://www.megavideo.com/xml/player_login.php?u={0}";

        public static string Referer
        {
            get
            {
                return "http://www.megavideo.com/";
            }
        }
        
        public List<string> GetMovieUrls(string content)
        {
            var movieCodes = new List<string>();
            var exp = new Regex(URL_REGEX, RegexOptions.IgnoreCase);
            var matches = exp.Matches(content);
            foreach (Match match in matches)
            {
                if (match.Success)
                {
                    var movieCode = string.Format(VIDEO_URL, match.Groups[1].Value);
                    if (!movieCodes.Contains(movieCode))
                    {
                        movieCodes.Add(movieCode);
                    }
                }
            }
            return movieCodes;
        }

        public VideoResult CheckVideoLink(string movieUrl)
        {
            var movieCode = new Regex(URL_REGEX, RegexOptions.IgnoreCase).Match(movieUrl).Groups[1].Value;
            var content = Utils.GetPage(string.Format(CONTROL_URI, movieCode), Encoding.Default);
            var match = new Regex("errortext=\"(.+?)\"", RegexOptions.IgnoreCase).Match(content);
            if (match.Success)
            {
                throw new Exception(match.Groups[1].Value);
            }

            var videoResult = new VideoResult(movieUrl, true)
                                  {
                                      VideoDetails = new VideoDetails
                                                         {
                                                             Description =
                                                                 GetValue(content,
                                                                          "description=\"(.+?)\""),
                                                             Size =
                                                                 GetValue(content,
                                                                          "size=\"(.+?)\""),
                                                             Runtime =
                                                                 GetValue(content,
                                                                          "runtimehms=\"(.+?)\""),
                                                             Name =
                                                                 GetValue(content,
                                                                          "title=\"(.+?)\""),
                                                             Category =
                                                                 GetValue(content,
                                                                          "category=\"(.+?)\"")
                                                         }
                                  };
            return videoResult;
        }

        private string GetValue(string content, string regEx)
        {
            var match = Regex.Match(content, regEx, RegexOptions.Singleline);
            if (!match.Success) return string.Empty;

            return Utils.LoopDecodeUrl(match.Groups[1].Value);
        }

        public VideoResult ExtractMovieUrl(string movieUrl)
        {
            var videoResult = CheckVideoLink(movieUrl);

            var premiumCode = Utils.GetMegaVideoPremium();
            if (!string.IsNullOrEmpty(premiumCode))
            {
                var movieCode = new Regex(URL_REGEX, RegexOptions.IgnoreCase).Match(movieUrl).Groups[1].Value;
                var extractUrl = string.Format(PREMIUM_URL, premiumCode, movieCode);
                var content = Utils.GetPage(extractUrl, Encoding.Default);
                var match = Regex.Match(content, "downloadurl=\"(.+?)\"", RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    var videoLink = Utils.LoopDecodeUrl(match.Groups[1].Value);
                    var splitedUrl = videoLink.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries);
                    var videoName = videoLink;
                    if(splitedUrl.Length > 0)
                    {
                        videoName = splitedUrl[splitedUrl.Length-1];
                    }
                    videoResult.Link = videoLink;
                    videoResult.MovieName = Utils.HtmlDecodeUrl(videoName);
                }
            }

            return videoResult;
        }

        public bool IsContainVideoLink(string url)
        {
            var match = Regex.Match(url, URL_REGEX, RegexOptions.IgnoreCase);
            return match.Success;
        }

        public string ConvertToMegaVideoLink(string link)
        {
            const string MOVIE_REGEX = "<div class=\"download_member_bl\".*?>.*?<a href=\"(.+?)\" class=\"download_premium_but\"></a>";
            var content = Utils.GetPage(link, Encoding.Default);
            var match = Regex.Match(content, MOVIE_REGEX, RegexOptions.Singleline);
            if (!match.Success || !match.Groups[1].Value.Contains("http"))
            {
                const string REGULAR_USER_URL =
                    "<a class=\"download_regular_disabled\"  id=\"dlbuttondisabled\"></a>.*?<a href=\"(.+?)\"";

                match = Regex.Match(content, REGULAR_USER_URL, RegexOptions.Singleline);
            }
            if( !match.Success ||
                match.Groups[1].Value.Contains(".rar") ||
                match.Groups[1].Value.Contains("zip"))
                return string.Empty;

            return match.Groups[1].Value;
        }

        public static bool IsPremiumMegaVideoUser(string cookieCode)
        {
            var checkUrl = string.Format(CHECK_PREMIUM_URL, cookieCode);
            var pageContent = Utils.GetPage(checkUrl, Encoding.UTF8);
            var match = Regex.Match(pageContent, "type=\"(.+?)\"", RegexOptions.IgnoreCase).Groups[1].Value;
            return match.Equals("premium");
        }
    }
}